package com.nononsenseapps.feeder

import android.os.Build

import androidx.multidex.MultiDexApplication
import com.gitee.wsl.common.more.ext.dialog.useXPopup
import com.gitee.wsl.common.more.ext.toast.useToasty
import com.gitee.wsl.common.ui.ext.ApplicationInit
import com.lzx.starrysky.StarrySkyInstall
import com.nononsenseapps.feeder.processor.RuleManager
import com.nononsenseapps.feeder.theme.appTheme
import com.nononsenseapps.feeder.util.EventBusUtils
import com.nononsenseapps.jsonfeed.trustHttpsURLConnectionAllCerts
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.*

import org.conscrypt.Conscrypt
import timber.log.Timber
import java.security.Security

abstract class AbstractFeederApplication: MultiDexApplication() {

    abstract fun isDebug():Boolean

    abstract suspend fun notifyCheck()

    override fun onCreate() {
        super.onCreate()

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Security.insertProviderAt(Conscrypt.newProvider(), 1)
        }
        MMKV.initialize(this)

        ApplicationInit.init(this){

            /*initToastInterface( object: ToastInit.ToastAdapter() {
                override fun toast(context: Context, text: String, duration: Int) {
                    Toasty.normal(context, text).show()
                }

                override fun toastSuccess(context: Context, label: String) {
                    Toasty.success(context, label, Toast.LENGTH_SHORT, true).show()
                }

                override fun toastError(context: Context, label: String) {
                    Toasty.error(context, label, Toast.LENGTH_LONG, true).show()
                }
            })*/

            crashHandler()

            useToasty()

            useXPopup(appTheme)
        }

        if (isDebug()) {
            Timber.plant(Timber.DebugTree())
        } else {
            Timber.plant(CrashReportingTree())
        }
        //LeakCanary.config= LeakCanary.config.copy(dumpHeap = false,retainedVisibleThreshold = 8)

        StarrySkyInstall.init(this).setDebug(isDebug()).setNotificationSwitch(true).apply()

        CoroutineScope(SupervisorJob()+Dispatchers.Default).launch {
            EventBusUtils.getNotifyStateFlow().collect{
                    notifyCheck()
                }
        }

        trustHttpsURLConnectionAllCerts()

        RuleManager.init(this)

    }
}

private class CrashReportingTree : Timber.Tree() {
    override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
        //if(priority == Log.ERROR)
         //com.simple.spiderman.SpiderMan.show(t)
    }
}
